import moment from 'moment'

const isNumber = (obj) => {
  return obj === +obj
}

export default {
  install (Vue) {
    Vue.prototype.Tools = {
      toPre (val) {
        if (isNumber(val)) {
          return (parseFloat(val) * 100).toFixed(2) + '%'
        }
      },
      toKtoM (val) {
        if (val !== null && typeof val !== 'string') {
          val = parseFloat(val).toString()
          // 数字过千万 就会 变成 k
          if (val < 1000) {
            let temp = parseFloat(val)
            return Number(temp).toLocaleString()
          }
          if (val >= 1000000000) {
            let temp = val / 1000000000
            return (
              Number(temp)
              .toFixed(1)
              .toLocaleString() + 'B'
            )
          }
          if (val >= 1000000 && val < 1000000000) {
            let temp = val / 1000000
            return (
              Number(temp)
              .toFixed(1)
              .toLocaleString() + 'M'
            )
          }
          if (val >= 1000 && val < 1000000) {
            let temp = val / 1000
            return (
              Number(temp)
              .toFixed(1)
              .toLocaleString() + 'K'
            )
          }
        } else {
          return val
        }
      },
      doKeyToArr (data, keyValue) {
        var newArr = []
        if (data && data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            for (var key in data[i]) {
              if (key === keyValue) {
                if (
                  Object.prototype.toString.call(data[i][key]) === '[object Number]'
                ) {
                  newArr.push(data[i][key] + 0)
                } else {
                  newArr.push(data[i][key])
                }
              }
            }
          }
          return newArr
        } else {
          return false
        }
      },
      formatDate (val, mask) {
        return moment(val).format(mask || 'YYYY-MM-DD')
      },
      formatNumber (number) {
        return parseFloat(number.toFixed(2)).toLocaleString()
      },
      trim (text) {
        if (typeof (text) === 'string') {
          return text.replace(/^\s*|\s*$/g, '')
        } else {
          return text
        }
      },
      rgba (color) {
        // let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
        let vals = color.slice(1).split('')
        let hex = []
        while (vals.length) {
          hex.push(vals.splice(0, 2).join(''))
        }
        let rgba = hex.map((h, i) => {
          let val = parseInt('0x' + h)
          if (i > 2) {
            return parseFloat((val / 255).toFixed(1))
          }
          return val
        })

        return `rgba(${rgba.join(',')})`
      },
      isNumber
    }
  }
}
